package User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Library {
    private List<Book> books;

    public Library() {
        books = loadBooksFromDatabase();
    }

    public List<Book> loadBooksFromDatabase() {
        List<Book> bookList = new ArrayList<>();
        String jdbcUrl = "jdbc:mysql://localhost:3306/bookmanagement";
        String username = "root";
        String password = "root";
        try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {
            String sql = "SELECT * FROM book";
            try (PreparedStatement statement = connection.prepareStatement(sql);
                 ResultSet resultSet = statement.executeQuery()) {
                while (resultSet.next()) {
                    String bookname = resultSet.getString("bookname");
                    String writer = resultSet.getString("writer");
                    Date addtime = resultSet.getDate("time");
                    String condition = resultSet.getString("condition");

                    Book book = new Book(bookname, writer, addtime,condition );
                    bookList.add(book);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return bookList;
    }
    public List<Book> searchByAuthor(String keyword) {
        return books.stream().filter(book -> book.getWriter().contains(keyword)).collect(Collectors.toList());
    }
    public List<Book> searchByTitle(String keyword) {
        return books.stream().filter(book -> book.getTitle().contains(keyword)).collect(Collectors.toList());
    }
    public List<Book> searchByAuthorAndTitle(String authorKeyword, String titleKeyword) {
        return books.stream().filter(book -> book.getWriter().contains(authorKeyword) && book.getTitle().contains(titleKeyword)).collect(Collectors.toList());
    }
    public List<Book> searchByAnyField(String keyword) {
        return books.stream()
                .filter(book -> book.getTitle().toLowerCase().contains(keyword.toLowerCase()) ||
                        book.getWriter().toLowerCase().contains(keyword.toLowerCase()))
                .collect(Collectors.toList());
    }
}
